package com.zbkj.service.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.zbkj.common.constants.CityWeightConfConstants;
import com.zbkj.common.model.project.CityWeight;
import com.zbkj.service.dao.project.CityWeightMapper;
import com.zbkj.service.service.project.CityWeightService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 省市权重配置表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-09-25
 */
@Service
public class CityWeightServiceImpl extends ServiceImpl<CityWeightMapper, CityWeight> implements CityWeightService {

    @Override
    public BigDecimal getWeightVal(String cityCode) {
        if(Objects.isNull(CityWeightConfConstants.CITY_WEIGHT_MAP)) {
            cityWeightCacheRefresh(0);
        }
        if(Objects.isNull(CityWeightConfConstants.CITY_WEIGHT_MAP)) {
            return null;
        }
        cityCode = StringUtils.isBlank(cityCode) ? "0" : cityCode;
        CityWeight weight = CityWeightConfConstants.CITY_WEIGHT_MAP.getOrDefault(cityCode, null);
        weight = Objects.isNull(weight) ?  CityWeightConfConstants.CITY_WEIGHT_MAP.getOrDefault("0",null) : weight;
        return Objects.isNull(weight) ? null : weight.getWeightVal();
    }

    @Override
    public List<CityWeight> getList() {
        LambdaQueryWrapper<CityWeight> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CityWeight::getDeleteFlag,0);
        return this.list(queryWrapper);
    }

    @Override
    public void cityWeightCacheRefresh(int forceFlag) {
        synchronized (CityWeightConfConstants.REFRESH_LOCK) {
            if(forceFlag == 0 && Objects.nonNull(CityWeightConfConstants.CITY_WEIGHT_MAP)) {
                return;
            }
            List<CityWeight> weightList = getList();
            if(CollectionUtils.isEmpty(weightList)) {
                return;
            }
            ConcurrentHashMap<String,CityWeight> cityWeightMap = new ConcurrentHashMap<>();
            for(CityWeight pojo : weightList) {
                cityWeightMap.put(pojo.getCityCode(), pojo);
            }
            CityWeightConfConstants.CITY_WEIGHT_MAP = cityWeightMap;
        }
    }

    @Override
    public BigDecimal getPerMonthFee(Integer projectType, String cityCode) {
        if(Objects.isNull(projectType)) {
            return null;
        }
        if(projectType == 1) {
            return this.getWeightVal(cityCode);
        } else if(projectType == 2) {
            return CityWeightConfConstants.JUN_PER_MONTH_FEE;
        }
        return null;
    }
}
